package com.iqilu.ksd.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.ADActivity;
import com.iqilu.ksd.activity.AddSubscribeActivity;
import com.iqilu.ksd.activity.GalleryActivity;
import com.iqilu.ksd.activity.LiveActivity;
import com.iqilu.ksd.activity.LoginActivity;
import com.iqilu.ksd.activity.MainActivity;
import com.iqilu.ksd.activity.MyActivity;
import com.iqilu.ksd.activity.MySubsActivity;
import com.iqilu.ksd.activity.NewsDetailActivity;
import com.iqilu.ksd.activity.PaikeActivity;
import com.iqilu.ksd.activity.RecommendListActivity;
import com.iqilu.ksd.activity.SubsDetailActivity;
import com.iqilu.ksd.adapter.subscribe.CatesAdapter;
import com.iqilu.ksd.adapter.subscribe.SubsDetailAdapter;
import com.iqilu.ksd.adapter.subscribe.SubsLightningAdapter;
import com.iqilu.ksd.adapter.subscribe.SubsRecAdapter;
import com.iqilu.ksd.bean.NewsBean;
import com.iqilu.ksd.bean.NewsItemBean;
import com.iqilu.ksd.bean.SubscribeBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.NewsType;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.event.SubsChangeEvent;
import com.iqilu.ksd.utils.BoxUtils;
import com.iqilu.ksd.utils.ConvertUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.widget.MyListView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import me.relex.circleindicator.CircleIndicator;
import okhttp3.Call;

/**
 * Created by Coofee on 2017/3/26.
 */

public class SubsFragment2 extends BaseFragment {

    private static final String TAG = "SubsFragment2";

    private UserBean user;
    private SubscribeBean data;

    private ImageView btLeft;
    private ImageView btRight;
    private TextView tvTitle;
    private ImageView btSubs;

    private RelativeLayout layCates;
    private ImageView imgIntoCates;
    private GridView gvCats;

    private MyListView lvSubsdetail;
    private MyListView lvRecommend;
    private ViewPager vpLightning;
    private TextView tvRecommend;

    private CatesAdapter catesAdapter;
    private SubsDetailAdapter subsDetailAdapter;
    private SubsRecAdapter subsRecAdapter;
    private SubsLightningAdapter subsLightningAdapter;

    private CircleIndicator layIndicator;
    private ImageView imgIntoRec;
    private RelativeLayout layLoading;
    private RelativeLayout layRetry;

    private static final int CODE_ADD_SUBS = 1001;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_subs2, null);
        user = ((MyApplication) context.getApplicationContext()).getUser();

        btLeft = getView(view, R.id.bt_left);
        btRight = getView(view, R.id.bt_right);
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) getActivity()).openDrawer();
            }
        });
        btRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, MyActivity.class));
            }
        });
        tvTitle = getView(view, R.id.tv_title);
        tvTitle.setText(getString(R.string.subs_title));
        setZHTypeface(tvTitle);
        btSubs = getView(view, R.id.bt_subs);
        layCates = getView(view, R.id.lay_cates);
        imgIntoCates = getView(view, R.id.img_into_cates);
        gvCats = getView(view, R.id.gv_cats);

        lvSubsdetail = getView(view, R.id.lv_subsdetail);
        lvRecommend = getView(view, R.id.lv_recommend);
        imgIntoRec = getView(view, R.id.img_into_rec);
        vpLightning = getView(view, R.id.vp_lightning);
        layIndicator = getView(view, R.id.lay_indicator);
        layLoading = getView(view, R.id.lay_loading);
        layRetry = getView(view, R.id.lay_retry);
        tvRecommend = getView(view, R.id.tv_recommend);
        setZHTypeface(tvRecommend);

        btSubs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user != null && user.getId() > 0) {
                    btSubs.setImageResource(R.drawable.bt_add_subs);
                    SPUtils.setPref(context, "subscribehash", data.getSubscribehash());
                    startActivityForResult(new Intent(context, AddSubscribeActivity.class),CODE_ADD_SUBS);
                } else {
                    startActivity(new Intent(context, LoginActivity.class));
                }
            }
        });
        gvCats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsBean bean = data.getCates().get(position);
                Intent intent = new Intent(context, SubsDetailActivity.class);
                intent.putExtra("catid", bean.getCatid());
                context.startActivity(intent);
            }
        });
        imgIntoCates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(context, MySubsActivity.class),CODE_ADD_SUBS);
            }
        });

        lvSubsdetail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsItemBean item = data.getInfos().get(position);
                onListItemClick(item);
            }
        });

        lvRecommend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsItemBean item = data.getJxinfos().get(position);
                onListItemClick(item);
            }
        });

        imgIntoRec.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, RecommendListActivity.class));
            }
        });

        layRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layLoading.setVisibility(View.VISIBLE);
                getList();
            }
        });

        getList();

        return view;
    }

    private void setData() {
        String subscribehash = SPUtils.getPref(context, "subscribehash", "");
        if (!subscribehash.equals(data.getSubscribehash())) {
            btSubs.setImageResource(R.drawable.bt_add_subs_dot);
        }
        if (data.getCates() == null || data.getCates().size() == 0) {
            layCates.setVisibility(View.GONE);
        } else {
            int size = data.getCates().size();
            int width = ConvertUtils.dp2px(context, 58) * size;
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MATCH_PARENT);
            gvCats.setLayoutParams(params);
            gvCats.setColumnWidth(ConvertUtils.dp2px(context, 48));
            gvCats.setHorizontalSpacing(10);
            gvCats.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);
            gvCats.setNumColumns(size);
            catesAdapter = new CatesAdapter(context);
            catesAdapter.setData(data.getCates());
            gvCats.setAdapter(catesAdapter);
            layCates.setVisibility(View.VISIBLE);
        }
        if (data.getInfos() == null || data.getInfos().size() == 0) {
            lvSubsdetail.setVisibility(View.GONE);
        } else {
            subsDetailAdapter = new SubsDetailAdapter(context);
            subsDetailAdapter.setData(data.getInfos());
            lvSubsdetail.setAdapter(subsDetailAdapter);
            lvSubsdetail.setVisibility(View.VISIBLE);
        }
        if (data.getJxinfos() == null || data.getJxinfos().size() == 0) {
            lvRecommend.setVisibility(View.GONE);
        } else {
            subsRecAdapter = new SubsRecAdapter(context);
            subsRecAdapter.setData(data.getJxinfos());
            lvRecommend.setAdapter(subsRecAdapter);
            lvRecommend.setVisibility(View.VISIBLE);
        }
        if (data.getTjinfos() != null && data.getTjinfos().size() == 8) {
            subsLightningAdapter = new SubsLightningAdapter(getChildFragmentManager(), context, data.getTjinfos());
            vpLightning.setAdapter(subsLightningAdapter);
            layIndicator.setViewPager(vpLightning, 4);
        }

    }

    private void getList() {
        String url = Api.URL_SBSCRIBE_MY;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                afterRefresh();
                layRetry.setVisibility(View.VISIBLE);
            }

            @Override
            public void onResponse(String response, int id) {
                afterRefresh();
                data = JSONUtils.requestDetail(response, "data", SubscribeBean.class);
                if (data == null) {
                    layRetry.setVisibility(View.VISIBLE);
                } else {
                    setData();
                }
            }
        });

    }

    private void afterRefresh() {
        layRetry.setVisibility(View.GONE);
        layLoading.setVisibility(View.GONE);
    }

    private void onListItemClick(NewsItemBean item) {
        Intent intent = null;
        if (item.getType().equals(NewsType.HEAD)) {
            item.setType(item.getRealtype());
        }
        if (item.getType().equals(NewsType.ARTICLE)) {
            intent = new Intent(context, NewsDetailActivity.class);
            intent.putExtra("id", item.getId());
            intent.putExtra("catId", item.getCatid());
        } else if (item.getType().equals(NewsType.GALLERY) || item.getType().equals(NewsType.PHOTO)) {
            intent = new Intent(context, GalleryActivity.class);
            intent.putExtra("id", item.getId());
            intent.putExtra("catId", item.getCatid());
            intent.putExtra("position", 0);
        } else if (item.getType().equals(NewsType.AD) || item.getType().equals(NewsType.URL)) {
            intent = new Intent(context, ADActivity.class);
            intent.putExtra("title", item.getTitle());
            intent.putExtra("type", item.getType());
            intent.putExtra("adUrl", item.getUrl());
            if (item.getType().equals(NewsType.AD)) {
                intent.putExtra("shareicon", item.getShareicon());
            } else {
                intent.putExtra("thumb", item.getThumb());
            }
        } else if (item.getType().equals(NewsType.LIVE)) {
            intent = new Intent(context, LiveActivity.class);
            intent.putExtra("id", item.getId());
        } else if (item.getType().equals(NewsType.CLUE)) {
            intent = new Intent(context, PaikeActivity.class);
            intent.putExtra("id", item.getId());
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    private void refresh(){
        user = ((MyApplication) context.getApplicationContext()).getUser();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getList();
            }
        }, 500);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK){
            switch (requestCode){
                case CODE_ADD_SUBS:
                    refresh();
                    break;
                default:
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessage(ChangeUserInfoEvent event) {
          refresh();
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessage(SubsChangeEvent event) {
        refresh();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

}
